﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Xml;

namespace Painter.Component
{
    class UpdateExe
    {
        public static bool Update()
        {
            try
            {
                string result = "";
                XmlDocument docXml = new XmlDocument();
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://api.platform.fssocks.com/api/v1/access/getlastedversion");
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.Headers.Add("AppID", "imageeditpc");
                req.Headers.Add("Sercert", "f02zXcmTGtk=");
                #region 添加Post 参数
                string requestParam = "{\"agent\": 90}";
                byte[] data = Encoding.UTF8.GetBytes(requestParam);
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                #endregion
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
                if (string.IsNullOrEmpty(result)) return false;
                Dictionary<string, object> obj = new JavaScriptSerializer().DeserializeObject(result) as Dictionary<string, object>;
                if ((int)obj["code"] == 200)
                {
                    string xmlFile = File.ReadAllText("Updater.xml");
                    docXml.LoadXml(xmlFile);
                    docXml.SelectSingleNode("/Update/Current/Version").InnerText = (obj["data"] as Dictionary<string, object>)["Versionnum"] as string;
                    docXml.SelectSingleNode("/Update/Lasted/Version").InnerText = (obj["data"] as Dictionary<string, object>)["Versionnum"] as string;
                    docXml.SelectSingleNode("/Update/Lasted/DownUrl").InnerText = (obj["data"] as Dictionary<string, object>)["Attachfileurl"] as string;
                    docXml.SelectSingleNode("/Update/ClientExe/PROCESSNAME").InnerText = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule.FileName);
                    docXml.Save("Updater.xml");
                    return true;
                }
                return false;
            }
            catch {
                return false;
            }
        }
    }
}
